package bootstrap

import (
	"context"
	"database/sql"
	"fmt"
	"os"

	"gitee.com/hp-huiw/family-expense-api/internal/security"
	"gitee.com/hp-huiw/family-expense-api/internal/service"
	"gitee.com/hp-huiw/my-go-core/config"
	libsecurity "gitee.com/hp-huiw/my-go-core/security"
)

// The function used to initialize application variables.
func init() {
	// Initializes current running environment mode.
	config.SysEnvMode = config.NewEnvMode()

	// Creates for configuration usage.
	config.ConfigLoader = config.NewAppConfigLoader()
}

func InitData(db *sql.DB) {
	ctx := context.Background()

	if err := service.NewAppReleaseLogService(db).Initialize(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing app release log: %v\n", err)
	}

	if err := service.NewBankService(db).Initialize(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing bank: %v\n", err)
	}

	if err := service.NewIncomeExpenseDetailBaseTypeService(db).Initialize(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing income expense detail base type: %v\n", err)
	}

	if err := service.NewRegionService(db).Initialize(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing region: %v\n", err)
	}

	if err := service.NewRequestMapService(db).Initialize(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing request map: %v\n", err)
	}

	if err := service.NewRoleService(db).Initialize(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing role: %v\n", err)
	}

	if err := libsecurity.ReloadCachedRequestMaps(ctx, security.NewSecurityRequestMapQuery(db)); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing request map: %v\n", err)
	}

	if err := security.NewUserActiveTokenManagerRepository(db).ReloadCachedUserActiveTokens(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing user active token: %v\n", err)
	}
}
